/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.brain.core.manager;

import com.brain.core.configuracion.WebServletContextListener;
import com.brain.core.dto.CorreoDto;

import com.brain.core.exception.ServiceException;
import com.brain.core.view.mbean.ApplicationMBean;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

/**
 *
 * @author Indra
 */
@Component
public class CorreoElectronicoManager {

    private static Logger logger = Logger.getLogger(CorreoElectronicoManager.class);
    private String mailServidor;
    private String mailFrom;
    private String mailFromPwd;
    private String mailPuerto;
    private String mailFromName;

    public int enviar(CorreoDto correoDto) throws ServiceException, UnsupportedEncodingException, MessagingException {
        Session session = null;
        ApplicationMBean applicationMBean = (ApplicationMBean) WebServletContextListener.getApplicationContext().getBean("applicationMBean");

        mailServidor = applicationMBean.getMailServidor();
        mailFrom = applicationMBean.getMailFrom();
        mailFromPwd = applicationMBean.getMailFromPwd();
        mailFromName = applicationMBean.getMailFromName();
        mailPuerto = applicationMBean.getMailPuerto();

        boolean continuar = true;
        StringBuilder mensaje = new StringBuilder();

        Properties propiedades = obtenerConfiguracion();
        session = obtenerSession(propiedades);

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mailFrom, mailFromName));

        InternetAddress[] iasTo = null;
        if (correoDto.getTo() != null && correoDto.getTo().length > 0) {
            continuar = true;
            iasTo = new InternetAddress[correoDto.getTo().length];
            int i = 0;
            for (String em : correoDto.getTo()) {
                iasTo[i++] = new InternetAddress(em);
            }
            message.setRecipients(Message.RecipientType.TO, iasTo);
            message.setSubject(correoDto.getAsunto());
            message.setContent(correoDto.getCuerpo(), "text/html");
            message.removeHeader("Content-Type");
            message.addHeader("Content-Type", "text/html");

        } else {
            continuar = false;
            mensaje.append("EL EMAIL NO SE HA ENVIADO PORQUE NO HAY NINGUN DESTINATARIO");
            return 0;
        }

        if (continuar) {
            InternetAddress[] iasCC = null;
            if (correoDto.getCc() != null && correoDto.getCc().length > 0) {
                continuar = true;
                iasCC = new InternetAddress[correoDto.getTo().length];
                int i = 0;
                for (String em : correoDto.getTo()) {
                    iasCC[i++] = new InternetAddress(em);
                }
                message.setRecipients(Message.RecipientType.CC, iasCC);
            }
        }

        if (continuar) {
            if (correoDto.getAdjuntos() != null && correoDto.getAdjuntos().length > 0) {
                MimeMultipart multiParte = new MimeMultipart();
                BodyPart body = null;
                FileDataSource fds = null;
                for (File f : correoDto.getAdjuntos()) {
                    body = new MimeBodyPart();
                    fds = new FileDataSource(f);
                    body.setDataHandler(new DataHandler(fds));
                    body.setFileName(f.getName());
                    multiParte.addBodyPart(body);
                }
                message.setContent(multiParte);
            }
        }


        if (continuar) {
            Transport.send(message);
            return 1;
        } else {
            return 0;
        }
    }

    private Properties obtenerConfiguracion() {
        Properties props = new Properties();
        props.put("mail.smtp.host", mailServidor);
        props.put("mail.smtp.socketFactory.port", mailPuerto);
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", mailPuerto);
        return props;
    }

    private Session obtenerSession(Properties props) {
        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(mailFrom,
                                mailFromPwd);
                    }
                });
        return session;
    }

  
}
